import {ExclamationCircleOutlined, PlusOutlined} from '@ant-design/icons';
import {Button, Form, Modal, Radio, Tag} from 'antd';
import React, {useState, useRef} from 'react';
import type {ProColumns, ActionType} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  ModalForm,
  ProFormSelect,
  ProFormTextArea,
} from '@ant-design/pro-form';
import {isSuccess} from "@/utils/utils";
import {OpResourcesManager} from "@/services/api-functions";
import {SYS_ENUMS} from "@/utils/constants";
import {history} from "umi";

export interface ResourceListProps {
  type: 'FREE'|'PAY'
  handlePublishStatus: Function
  handleAudit: Function
  handleDelete: Function
  recommend: Function
}


const ResourceList: React.FC<ResourceListProps> = ({type, handleAudit, handlePublishStatus, handleDelete, recommend}) => {

  const [auditFormRef] = Form.useForm()
  const [auditState, setAuditState] = useState<'ALL'|'IN'|'PASS'|'REFUSE'>('ALL');
  const [countInfo, setCountInfo] = useState<{all: number, in: number, pass: number, refuse: number}>({all:0, in: 0, pass: 0, refuse: 0});
  const [auditVisible, handleAuditVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<any>();
  const payColumns: ProColumns[] = [{
    title: '加入会员',
    dataIndex: 'membersFree',
    valueEnum: SYS_ENUMS.BOOLEAN_ENUMS,
    width: 100,
    hideInSearch: true,
    hideInForm: true,
  },{
    title: '售价',
    dataIndex: 'sellingPrice',
    ellipsis: true,
    hideInSearch: true,
    width: 100,
  },{
    title: '购买量',
    dataIndex: 'tradingNum',
    ellipsis: true,
    hideInSearch: true,
    width: 100,
  },];
  const freeColumns: ProColumns[] = [{
    title: '下载量',
    dataIndex: 'tradingNum',
    ellipsis: true,
    hideInSearch: true,
    width: 100,
  },];
  const columns: ProColumns[] = [
    {
      title: '标题',
      dataIndex: 'title',
      ellipsis: true,
      width: 350,
      fixed: 'left'
    },
    {
      title: '分类',
      dataIndex: 'classification',
      valueEnum: SYS_ENUMS.RESOURCE_CLASSIFICATION,
      width: 100,
    },
    {
      title: '设计师',
      dataIndex: ['userDto', 'nickName'],
      ellipsis: true,
      hideInSearch: true,
      width: 120,
    },
    {
      title: '审核状态',
      dataIndex: 'auditState',
      valueEnum: SYS_ENUMS.RESOURCE_AUDIT_STATE,
      width: 130,
      hideInForm: true,
      hideInSearch: true,
    }, {
      title: '资源状态',
      dataIndex: 'sellingState',
      valueEnum: SYS_ENUMS.RESOURCE_STATUS,
      width: 130,
      hideInForm: true,
    },
    {
      title: '是否推荐',
      dataIndex: 'recommend',
      valueEnum: SYS_ENUMS.BOOLEAN_ENUMS,
      width: 100,
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '浏览量',
      dataIndex: 'browseNum',
      ellipsis: true,
      hideInSearch: true,
      width: 100,
    },
    {
      title: '收藏量',
      dataIndex: 'focusNum',
      ellipsis: true,
      hideInSearch: true,
      width: 100,
    },
    {
      title: '评论数',
      dataIndex: 'replyNum',
      ellipsis: true,
      hideInSearch: true,
      width: 100,
    },];
  const endColumns: ProColumns[] = [
    {
      title: '发布时间',
      dataIndex: 'gmtCreate',
      valueType: 'dateTime',
      width: 170,
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInSearch: true,
      hideInForm: true,
      width: 300,
      fixed: 'right',
      render: (_, record) => [
        <a key="edit" href={`/resource/detail/${record?.id}`}>详情</a>,
        <a key="edit" onClick={()=>history.push(`/resource/edit/${record.id}`)}>编辑</a>,
        <a key="edit"
           onClick={() => Modal.confirm({
             title: '提示',
             icon: <ExclamationCircleOutlined/>,
             content: <span>确定要删除 <Tag color='#108ee9'>{record.title}</Tag> 吗？</span>,
             okText: '删除',
             cancelText: '取消',
             onOk: async () => {
               if (await handleDelete(record)) {
                 actionRef.current?.reload()
               }
             },
           })}
        >删除</a>,
        (
          record.auditState === SYS_ENUMS.RESOURCE_AUDIT_STATE.ING.value
            ? <a key="edit" onClick={() => {
              setCurrentRow(record)
              auditFormRef?.resetFields()
              handleAuditVisible(true)
            }}>审核</a> : null
        ),
        record.auditState === SYS_ENUMS.RESOURCE_AUDIT_STATE.PASS.value ? (
          record.sellingState === 'UP'
            ? <a key="edit" onClick={() => Modal.confirm({
              title: '提示',
              icon: <ExclamationCircleOutlined/>,
              content: <span>确定要下架 <Tag color='#108ee9'>{record.title}</Tag> 吗？</span>,
              okText: '下架',
              cancelText: '取消',
              onOk: async () => {
                if (await handlePublishStatus(record, 'DOWN')) {
                  actionRef.current?.reload()
                }
              },
            })}>下架</a>
            : <a key="edit" onClick={() => Modal.confirm({
              title: '提示',
              icon: <ExclamationCircleOutlined/>,
              content: <span>确定要上架 <Tag color='#108ee9'>{record.title}</Tag> 吗？</span>,
              okText: '上架',
              cancelText: '取消',
              onOk: async () => {
                if (await handlePublishStatus(record, 'UP')) {
                  actionRef.current?.reload()
                }
              },
            })}>上架</a>
        ) : null,
        record.recommend !== 1
          ? <a key="edit" onClick={() => Modal.confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined/>,
            content: <span>确定要设置 <Tag color='#108ee9'>{record.title}</Tag> 推荐吗？</span>,
            okText: '设为推荐',
            cancelText: '取消',
            onOk: async () => {
              if (await recommend(record, 1)) {
                actionRef.current?.reload()
              }
            },
          })}>设为推荐</a>
          : <a key="edit" onClick={() => Modal.confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined/>,
            content: <span>确定要取消推荐 <Tag color='#108ee9'>{record.title}</Tag> 吗？</span>,
            okText: '取消推荐',
            cancelText: '取消',
            onOk: async () => {
              if (await recommend(record, 0)) {
                actionRef.current?.reload()
              }
            },
          })}>取消推荐</a>,
      ],
    },
  ]
  return (
    <>
      <ProTable<any, any>
        headerTitle={<Radio.Group value={auditState} onChange={(e) => {
          setAuditState(e.target.value)
          actionRef.current?.reload()
        }}>
          <Radio.Button value='ALL'>全部 {countInfo?.all ?? 0}</Radio.Button>
          <Radio.Button value='ING'>待审核 {countInfo?.in ?? 0}</Radio.Button>
          <Radio.Button value='PASS'>已通过 {countInfo?.pass ?? 0}</Radio.Button>
          <Radio.Button value='REFUSE'>未通过 {countInfo?.refuse ?? 0}</Radio.Button>
        </Radio.Group>}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => history.push('/resource/edit')}>
            <PlusOutlined/> 新建
          </Button>,
          <Button onClick={() => history.push('/resource/comments')}>评论列表</Button>,
          <Button onClick={() => {}}>订单列表</Button>,
        ]}
        request={async (params) => {

          const query = {...params, paymentType: type}
          if (auditState !== 'ALL') {
            query.auditState = auditState
          }

          const {data: {data, total}, code}: any = await OpResourcesManager.pageQuery(query);

          const res = await OpResourcesManager.resourcesCountInfo(type);

          if(isSuccess(res.code)){
            setCountInfo(res.data)
          }

          return {data: data || [], success: isSuccess(code), total: isSuccess(code) ? total : 0};
        }}
        columns={[...columns, ...(type === "PAY" ? payColumns : freeColumns), ...endColumns]}
        scroll={{ x: 1300 }}
      />

      <ModalForm
        title={`审核【${currentRow?.title}】`}
        width="750px"
        form={auditFormRef}
        visible={auditVisible}
        onVisibleChange={v => {
          handleAuditVisible(v)
          if (!v) {
            auditFormRef?.resetFields()
          }
        }}
        onFinish={async (value) => {
          // @ts-ignore
          if (await handleAudit(value as any, currentRow)) {
            handleAuditVisible(false);
            auditFormRef?.resetFields()
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormSelect label='审核结果' required rules={[{required: true, message: '请填选择审核结果',},]} name='auditOperate'
                       initialValue={SYS_ENUMS.RESOURCE_AUDIT_STATE.PASS.value} options={[
          {label: SYS_ENUMS.RESOURCE_AUDIT_STATE.PASS.label, value: SYS_ENUMS.RESOURCE_AUDIT_STATE.PASS.value},
          {label: SYS_ENUMS.RESOURCE_AUDIT_STATE.REFUSE.label, value: SYS_ENUMS.RESOURCE_AUDIT_STATE.REFUSE.value},
        ]}/>
        <ProFormTextArea label='备注' name="remark"/>
      </ModalForm>
    </>
  );
};

export default ResourceList;
